
<template>
    <div class="login-page" :style="{ backgroundImage: `url(${loginBg})` }">
      <div class="top-bar">
        <el-icon class="logo-icon">
          <img src="../assets/icon/LOGO.png" alt="Logo" />
        </el-icon>
        <div class="logo-text" style="color: yellow; font-family: 'ArtisticFontFamily';">
          红星智慧党建平台
        </div>
      </div>
  
      <div class="main-content">
        <el-card class="auth-card" style="padding: 20px;"> <!-- 添加内边距 -->
          <div class="card-icon">
            <el-icon><UserFilled /></el-icon>
          </div>
  
          <el-form v-if="!showRegister" :model="loginForm" :rules="loginRules" ref="loginForm">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="用户名">
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="loginForm.password" 
                :type="passwordVisible ? 'text' : 'password'" 
                placeholder="密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
                <template #suffix>
                  <el-icon @click="togglePasswordVisibility" style="cursor: pointer;">
                    <View v-if="!passwordVisible" />
                    <Hide v-else />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
  
            <el-form-item prop="captcha">
              <el-input v-model="loginForm.captcha" placeholder="验证码">
                <template #prefix>
                  <el-icon><Tickets /></el-icon>
                </template>
              </el-input>
              <span class="captcha-code">{{ captchaCode }}</span>
              <el-button @click="generateCaptcha" class="refresh-captcha">刷新验证码</el-button>
            </el-form-item>
  
            <el-form-item class="form-buttons">
              <el-button type="primary" @click="login">登录</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
  
            <div class="register-link">
              <span @click="toggleRegister">还没有账户？去注册 →</span>
            </div>
          </el-form>
  
          <el-form v-else :model="registerForm" :rules="registerRules" ref="registerForm">
            <el-form-item prop="email">
              <el-input v-model="registerForm.email" placeholder="邮箱">
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="username">
              <el-input v-model="registerForm.username" placeholder="用户名">
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" type="password" placeholder="密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="repeatPassword">
              <el-input v-model="registerForm.repeatPassword" type="password" placeholder="重复输入密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
  
            <el-form-item>
              <el-button type="primary" @click="register" style="width: 350px;">注册</el-button>
            </el-form-item>
            <div class="login-link">
              <span @click="toggleRegister">已有账户？去登录 ←</span>
            </div>
          </el-form>
        </el-card>
      </div>
  
      <div class="bottom-bar">
        © 版权信息
      </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import loginBg from '../assets/bac/Login-bac.jpg';
  import { User, Lock, Tickets, UserFilled, Message } from '@element-plus/icons-vue'; // 不再需要 Notebook
  import { View, Hide } from '@element-plus/icons-vue';
  
  export default {
    components: {
      User,
      Lock,
      Tickets,
      UserFilled,
      Message,
      View,
      Hide
    },
    data() {
      return {
        loginBg,
        loginForm: {
          username: '',
          password: '',
          captcha: ''
        },
        registerForm: {
          email: '',
          username: '',
          password: '',
          repeatPassword: ''
        },
        showRegister: false,
        passwordVisible: false,
        captchaCode: '',
        loginRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 5, max: 11, message: '用户名长度在5到11位之间', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 11, message: '密码长度在6到11位之间', trigger: 'blur' }
          ],
          captcha: [
            { required: true, message: '请输入验证码', trigger: 'blur' }
          ]
        },
        registerRules: {
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' }
          ],
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 5, max: 11, message: '用户名长度在5到11位之间', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 11, message: '密码长度在6到11位之间', trigger: 'blur' }
          ],
          repeatPassword: [
            { required: true, message: '请确认密码', trigger: 'blur',
              validator: (rule, value, callback) => {
                if (value !== this.registerForm.password) {
                  callback(new Error('两次密码输入不一致'));
                } else {
                  callback();
                }
              }
            }
          ]
        }
      };
    },
    mounted() {
      this.generateCaptcha();
    },
    methods: {
      togglePasswordVisibility() {
        this.passwordVisible = !this.passwordVisible;
      },
      async login() {
        this.$refs.loginForm.validate(async (valid) => {
          if (valid) {
            try {
              const response = await axios.post('/api/login', this.loginForm);
              const { success, token, role, userId } = response.data;
  
              if (success) {
                localStorage.setItem('token', token);
                localStorage.setItem('role', role);
                localStorage.setItem('userId', userId);
                this.$message.success('登录成功');
                this.$router.push(role === 'admin' ? '/admin' : '/user/home');
              } else {
                this.$message.error('登录失败');
                this.resetForm();
              }
            } catch (error) {
              console.error(error);
              this.$message.error('登录请求失败');
              this.resetForm();
            }
          }
        });
      },
      async register() {
        this.$refs.registerForm.validate(async (valid) => {
          if (valid) {
            try {
              const response = await axios.post('/api/register', this.registerForm);
              const { success, message } = response.data;
  
              if (success) {
                this.$message.success('注册成功，转到登录界面');
                this.loginForm.username = this.registerForm.username;
                this.toggleRegister();
                this.resetForm();
              } else {
                this.$message.error(`注册失败: ${message}`);
              }
            } catch (error) {
              console.error(error);
              this.$message.error('注册请求失败');
            }
          }
        });
      },
      toggleRegister() {
        this.showRegister = !this.showRegister;
      },
      generateCaptcha() {
        this.captchaCode = Math.random().toString(36).substring(2, 6).toUpperCase();
      },
      resetForm() {
        if (this.showRegister && this.$refs.registerForm) {
          this.$refs.registerForm.resetFields();
        } else if (!this.showRegister && this.$refs.loginForm) {
          this.$refs.loginForm.resetFields();
        }
      }
    },
  };
  </script>
  
  <style lang="scss" scoped>
  @import '../assets/scss/LoginPage.scss';
  .login-page {
    background-size: cover; /* 背景图片覆盖 */
    padding: 20px; /* 整体内边距 */
  }
  </style>
  